import { servicesUrl } from './config'
const CODE_SUCCESS = 200; //成功的状态码
const CODE_AUTH_EXPIRED = 401 //清除缓存的状态码
export default function axios(options) {
	const { url, payload = {}, method = 'GET', autoLogin = true, showToast = true, queryString = false } = options;
	const access_token = uni.getStorageSync('token');
	const header = access_token ? { 'X-Mp-token': access_token } : {};
	if (method == 'GET' || queryString) {
		header['content-type'] = 'application/x-www-form-urlencoded';
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: servicesUrl + url,
			method,
			data: { ...payload },
			header,
			success: res => {
				console.log('unirequeset',res)
				const { statusCode, data } = res;
				if (statusCode !== CODE_SUCCESS) {
					if (showToast) {
						uni.showToast({
							title: data.code == CODE_AUTH_EXPIRED ? data.message : '请求异常',
							icon: 'none'
						})
					}
					if (data.code == CODE_AUTH_EXPIRED) {
						//uni.clearStorageSync();
					}
					reject(res.errMsg);
				}
				if (data.code !== 0) {				
					if (data.code == CODE_AUTH_EXPIRED) {
						//uni.clearStorageSync();
						if (autoLogin) {
							uni.navigateTo({
								url: "/pages/login/login"
							});
						}
					}
					if(typeof(data) == 'string'){
						resolve(data);
					}else{
						const defaultMsg = (data.code == CODE_AUTH_EXPIRED) ? '登录已过期' : (data && data.message) || '请求异常';
						if (showToast) {
							uni.showToast({
								title: defaultMsg,
								icon: 'none'
							})
						}
						reject(data);
					}
				}
				resolve(data);
			},
			fail: err => {
				if (err.errMsg.includes("request:fail")) {
					uni.showToast({ title: '请求超时', icon: 'none' })
				}
				reject(err);
			}
		})
	})
}
